﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace BlogBobby
{
    public class BlogService : IBlogService
    {
        public IEnumerable<PostDTO> RetrievePosts(string nn, string cc)
        {
            int c = int.Parse(cc);
            int n = int.Parse(nn);

            BlogBobbyEntities context = new BlogBobbyEntities();
            var res = (from p in context.Posts
                       orderby p.Date descending
                       select p).Take(n);

            List<PostDTO> result = new List<PostDTO>();
            foreach (var item in res)
            {
                PostDTO post = PostDTO.GetFromPost(item);
                if(c < post.Body.Length)
                    post.Body = post.Body.Substring(0, c);
                result.Add(post);
            }
            return result;
        }

        public PostDTO RetrieveSinglePost(string id, string m)
        {
            int i = int.Parse(id);
            int n = int.Parse(m);

            BlogBobbyEntities context = new BlogBobbyEntities();

            var res = (from p in context.Posts
                       where p.PostID == i
                       select p).SingleOrDefault();

            if (res != null)
            {
                PostDTO result = PostDTO.GetFromPost(res);

                var comments = (from c in res.Comments
                                orderby c.Date descending
                                select CommentDTO.CreateFromComment(c)).Take(n);

                result.PostComments = new List<CommentDTO>(comments);

                return result;
            }
            return null;
        }

        public void PostComment(CommentDTO commentToPost)
        {
            BlogBobbyEntities context = new BlogBobbyEntities();
            Comment toAdd = commentToPost.ToComment();
            context.Comments.AddObject(toAdd);
            context.SaveChanges();            
        }
    }
}
